<template>
	<view class="container">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar-content">
				<view class="navbar-title">账号本子</view>
				<view class="navbar-right">
					<view class="icon-wrapper" @click="handleSearch">
						<uni-icons type="search" size="32" color="#FFFFFF"></uni-icons>
					</view>
					<view class="icon-wrapper" @click="handleAdd">
						<uni-icons type="plus" size="32" color="#FFFFFF"></uni-icons>
					</view>
					<view class="icon-wrapper" @click="handleMenu">
						<uni-icons type="bars" size="32" color="#FFFFFF"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 主内容区 -->
		<view class="main-content" :style="{ marginTop: (statusBarHeight + 44) + 'px' }">
			<!-- 左侧分类列表 -->
			<scroll-view class="category-list" scroll-y>
				<view 
					class="category-item" 
					:class="{ active: activeCategory === item.id }"
					v-for="item in categories" 
					:key="item.id"
					@click="selectCategory(item.id)"
				>
					<text>{{ item.name }}</text>
				</view>
				<view class="category-item settings-icon" @click="handleAddTag">
					<uni-icons type="gear" size="20" color="#CCCCCC"></uni-icons>
				</view>
			</scroll-view>

			<!-- 右侧账号列表 -->
			<scroll-view class="account-list" scroll-y>
				<view class="account-item" v-for="account in filteredAccounts" :key="account.id" @click="openAccountDetail(account)" @longpress="handleAccountLongPress(account)">
					<view class="account-icon" :style="{ backgroundColor: account.color }"></view>
					<view class="account-info">
						<view class="account-name">{{ account.name }}</view>
						<view class="account-subtitle">{{ account.subtitle }}</view>
					</view>
				</view>
			</scroll-view>

			<!-- 右侧字母索引 -->
			<view 
				class="alphabet-index"
				@touchstart.prevent.stop="handleIndexTouchStart"
				@touchmove.prevent.stop="handleIndexTouchMove"
				@touchend.prevent.stop="handleIndexTouchEnd"
			>
				<view class="index-star" :class="{ active: currentIndex === 'star' }">
					<text>☆</text>
				</view>
				<view 
					class="index-letter" 
					:class="{ active: currentIndex === letter }"
					v-for="letter in alphabet" 
					:key="letter"
					:data-letter="letter"
				>
					<text>{{ letter }}</text>
				</view>
				<view class="index-letter" :class="{ active: currentIndex === '#' }" data-letter="#">
					<text>#</text>
				</view>
		</view>
		</view>

		<!-- 底部指示器 -->
		<view class="bottom-indicator"></view>

		<!-- 账号详情弹窗 -->
		<account-detail-modal 
			:visible="showAccountModal"
			:account-detail="selectedAccount"
			@close="closeAccountModal"
			@toggle-favorite="toggleFavorite"
			@edit="handleEditAccount"
		></account-detail-modal>

		<!-- 账号操作菜单 -->
		<!-- <account-action-modal 
			:visible="showActionModal"
			:account-name="longPressAccount?.name || ''"
			:is-favorite="longPressAccount?.isFavorite || false"
			@close="closeActionModal"
			@edit="handleActionEdit"
			@toggle-favorite="handleActionToggleFavorite"
			@create-from-template="handleCreateFromTemplate"
			@copy-all="handleCopyAll"
			@delete="handleDeleteAccount"
		></account-action-modal> -->

		<!-- 删除账号确认弹窗 -->
		<delete-account-confirm-modal 
			:visible="showDeleteConfirmModal"
			:account-name="deleteAccountName"
			@close="closeDeleteConfirmModal"
			@confirm="confirmDeleteAccount"
		></delete-account-confirm-modal>
	</view>
</template>

<script>
	import AccountDetailModal from '@/components/Modal/account-detail-modal.vue'
	// import AccountActionModal from '@/components/Modal/account-action-modal.vue'
	import DeleteAccountConfirmModal from '@/components/Modal/delete-account-confirm-modal.vue'
	import { getAllAccounts, initDefaultAccounts, toggleFavorite, getAccountById, deleteAccount } from '@/utils/accountService.js';
	import { getAllTags, initDefaultTags } from '@/utils/tagService.js';
	
	export default {
		components: {
			AccountDetailModal,
			// AccountActionModal,
			DeleteAccountConfirmModal
		},
		data() {
			return {
				statusBarHeight: 0,
				activeCategory: 'all',
				searchKeyword: '',
				currentIndex: '',
				isIndexTouching: false,
				categories: [
					{ id: 'all', name: '全部账号' },
					{ id: 'favorite', name: '我的收藏' }
				],
				accounts: [],
				alphabet: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
				showAccountModal: false,
				selectedAccount: {},
				selectedAccountId: null,
				showActionModal: false,
				longPressAccount: null,
				showDeleteConfirmModal: false,
				deleteAccountId: null,
				deleteAccountName: ''
			}
		},
		onLoad() {
			// 获取状态栏高度
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight || 20;
			
			// 初始化默认数据
			initDefaultTags();
			initDefaultAccounts();
			
			// 加载数据
			this.loadData();
		},
		onShow() {
			// 页面显示时重新加载数据（从其他页面返回时）
			this.loadData();
		},
		computed: {
			filteredAccounts() {
				let result = this.accounts;
				
				// 按分类筛选
				if (this.activeCategory === 'favorite') {
					result = result.filter(account => account.isFavorite === true);
				} else if (this.activeCategory !== 'all') {
					// 根据标签筛选
					result = result.filter(account => account.tag === this.activeCategory);
				}
				
				// 按搜索关键词筛选
				if (this.searchKeyword) {
					const keyword = this.searchKeyword.toLowerCase();
					result = result.filter(account => 
						account.name.toLowerCase().includes(keyword) || 
						(account.subtitle && account.subtitle.toLowerCase().includes(keyword)) ||
						(account.account && account.account.toLowerCase().includes(keyword))
					);
				}
				
				return result;
			}
		},
		methods: {
			loadData() {
				// 加载账号列表
				this.accounts = getAllAccounts();
				
				// 加载标签并更新分类列表
				const tags = getAllTags();
				const tagCategories = tags.map(tag => ({
					id: tag.name,
					name: tag.name
				}));
				
				this.categories = [
					{ id: 'all', name: '全部账号' },
					{ id: 'favorite', name: '我的收藏' },
					...tagCategories
				];
			},
			selectCategory(id) {
				this.activeCategory = id;
			},
			handleAdd() {
				uni.navigateTo({
					url: '/pages/add-account/add-account',
					fail: (err) => {
						// uni.showToast({
						// 	title: '请重新运行项目',
						// 	icon: 'none',
						// 	duration: 2000
						// });
					}
				});
			},
			handleSearch() {
				// 跳转到搜索页面，传递账号总数
				const totalAccounts = this.accounts.length;
				// 使用绝对路径，确保在不同环境下都能正常跳转
				const url = `/pages/search/search?totalAccounts=${totalAccounts}`;
				
				uni.navigateTo({
					url: url,
					fail: (err) => {
						// uni.showToast({
						// 	title: '请重新运行项目',
						// 	icon: 'none',
						// 	duration: 2000
						// });
					}
				});
			},
			handleMenu() {
				uni.navigateTo({
					url: '/pages/settings/settings'
				});
			},
			handleAddTag() {
				// 跳转到标签管理页面
				uni.navigateTo({
					url: '/pages/tag-management/tag-management',
					fail: (err) => {
						// uni.showToast({
						// 	title: '请重新运行项目',
						// 	icon: 'none',
						// 	duration: 2000
						// });
					}
				});
			},
			// 字母索引触摸开始
			handleIndexTouchStart(e) {
				e.preventDefault && e.preventDefault();
				e.stopPropagation && e.stopPropagation();
				this.isIndexTouching = true;
				this.handleIndexTouch(e);
			},
			// 字母索引触摸移动
			handleIndexTouchMove(e) {
				if (!this.isIndexTouching) return;
				e.preventDefault && e.preventDefault();
				e.stopPropagation && e.stopPropagation();
				this.handleIndexTouch(e);
			},
			// 字母索引触摸结束
			handleIndexTouchEnd(e) {
				e.preventDefault && e.preventDefault();
				e.stopPropagation && e.stopPropagation();
				this.isIndexTouching = false;
				// 延迟清除选中状态，让用户能看到最后选中的字母
				setTimeout(() => {
					this.currentIndex = '';
				}, 200);
			},
			// 处理字母索引触摸
			handleIndexTouch(e) {
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.alphabet-index').boundingClientRect((indexRect) => {
						if (!indexRect) return;
						
						query.selectAll('.index-star, .index-letter').boundingClientRect((rects) => {
							if (!rects || rects.length === 0) return;
							
							// 优先使用 changedTouches（touchmove/touchend），否则使用 touches（touchstart）
							const touch = e.changedTouches && e.changedTouches.length > 0 
								? e.changedTouches[0] 
								: (e.touches && e.touches.length > 0 ? e.touches[0] : null);
							
							if (!touch) return;
							
							const touchY = touch.clientY || touch.pageY;
							const indexTop = indexRect.top;
							
							// 计算相对位置
							const relativeY = touchY - indexTop;
							
							// 遍历所有索引项，找到触摸位置对应的字母
							for (let i = 0; i < rects.length; i++) {
								const rect = rects[i];
								// rect.top 已经是相对于页面的绝对位置
								const itemTop = rect.top - indexTop;
								const itemBottom = itemTop + rect.height;
								
								if (relativeY >= itemTop && relativeY <= itemBottom) {
									let letter = '';
									if (i === 0) {
										letter = 'star';
									} else if (i === rects.length - 1) {
										letter = '#';
									} else {
										letter = this.alphabet[i - 1];
									}
									
									if (this.currentIndex !== letter) {
										this.currentIndex = letter;
										if (letter !== 'star' && letter !== '#') {
											this.scrollToLetter(letter);
										} else if (letter === 'star') {
											this.scrollToTop();
										} else {
											this.scrollToBottom();
										}
									}
									break;
								}
							}
						}).exec();
					}).exec();
				});
			},
			scrollToLetter(letter) {
				// 滚动到对应字母位置
				// TODO: 实现滚动到对应字母的逻辑
			},
			scrollToTop() {
				// 滚动到顶部
				// TODO: 实现滚动到顶部的逻辑
			},
			scrollToBottom() {
				// 滚动到底部
				// TODO: 实现滚动到底部的逻辑
			},
			openAccountDetail(account) {
				this.selectedAccountId = account.id;
				
				this.selectedAccount = {
					name: account.name || '',
					account: account.account || account.subtitle || '',
					password: account.password || '',
					note: account.note || '',
					isFavorite: account.isFavorite || false,
					tag: account.tag || '',
					lastModified: account.lastModified || new Date().toLocaleString('zh-CN', {
						year: 'numeric',
						month: '2-digit',
						day: '2-digit',
						hour: '2-digit',
						minute: '2-digit',
						second: '2-digit',
						hour12: false
					}).replace(/\//g, '-').replace(',', ''),
					customFields: account.customFields || {} // 传递自定义字段
				};
				this.showAccountModal = true;
			},
			closeAccountModal() {
				this.showAccountModal = false;
				this.selectedAccountId = null;
			},
			toggleFavorite(isFavorite) {
				if (this.selectedAccountId) {
					try {
						const updatedAccount = toggleFavorite(this.selectedAccountId);
						if (updatedAccount) {
							this.selectedAccount.isFavorite = updatedAccount.isFavorite;
							// 重新加载数据以更新列表
							this.loadData();
						}
					} catch (error) {
						// uni.showToast({
						// 	title: error.message || '操作失败',
						// 	icon: 'none'
						// });
					}
				}
			},
			handleEditAccount() {
				// 先从当前账号对象中获取ID，如果不行再用selectedAccountId
				let accountId = null;
				const currentAccount = this.accounts.find(a => a.id === this.selectedAccountId);
				if (currentAccount && currentAccount.id) {
					accountId = currentAccount.id;
				} else if (this.selectedAccountId) {
					accountId = this.selectedAccountId;
				}
				
				if (!accountId) {
					// uni.showToast({
					// 	title: '无法获取账号ID',
					// 	icon: 'none'
					// });
					return;
				}
				
				// 关闭详情弹窗
				this.closeAccountModal();
				
				// 跳转到编辑页面，传递账号ID（确保是数字）
				uni.navigateTo({
					url: `/pages/add-account/add-account?accountId=${accountId}`,
					fail: (err) => {
						// uni.showToast({
						// 	title: '跳转失败',
						// 	icon: 'none',
						// 	duration: 2000
						// });
					}
				});
			},
			// 长按账号
			handleAccountLongPress(account) {
				this.longPressAccount = account;
				this.showActionModal = true;
			},
			// 关闭操作菜单
			closeActionModal() {
				this.showActionModal = false;
				this.longPressAccount = null;
			},
			// 操作菜单 - 编辑
			handleActionEdit() {
				if (!this.longPressAccount || !this.longPressAccount.id) {
					// uni.showToast({
					// 	title: '无法获取账号ID',
					// 	icon: 'none'
					// });
					return;
				}
				
				// 先保存账号ID，再关闭模态框
				const accountId = this.longPressAccount.id;
				this.closeActionModal();
				
				uni.navigateTo({
					url: `/pages/add-account/add-account?accountId=${accountId}`,
					fail: (err) => {
						// uni.showToast({
						// 	title: '跳转失败',
						// 	icon: 'none',
						// 	duration: 2000
						// });
					}
				});
			},
			// 操作菜单 - 切换收藏
			handleActionToggleFavorite() {
				if (!this.longPressAccount || !this.longPressAccount.id) {
					// uni.showToast({
					// 	title: '操作失败',
					// 	icon: 'none'
					// });
					return;
				}
				
				// 先保存账号ID，再关闭模态框
				const accountId = this.longPressAccount.id;
				this.closeActionModal();
				
				try {
					const updatedAccount = toggleFavorite(accountId);
					if (updatedAccount) {
						this.loadData();
					}
				} catch (error) {
					// uni.showToast({
					// 	title: error.message || '操作失败',
					// 	icon: 'none'
					// });
				}
			},
			// 操作菜单 - 作为模版新建
			handleCreateFromTemplate() {
				if (!this.longPressAccount || !this.longPressAccount.id) {
					// uni.showToast({
					// 	title: '无法获取账号信息',
					// 	icon: 'none'
					// });
					return;
				}
				
				// 先保存账号ID，再关闭模态框
				const templateId = this.longPressAccount.id;
				this.closeActionModal();
				
				// 使用 URL 参数传递模版账号ID，在添加页面中加载完整数据作为模版
				uni.navigateTo({
					url: `/pages/add-account/add-account?template=1&templateId=${templateId}`,
					fail: (err) => {
						// uni.showToast({
						// 	title: '跳转失败',
						// 	icon: 'none',
						// 	duration: 2000
						// });
					}
				});
			},
			// 操作菜单 - 复制全部内容
			handleCopyAll() {
				if (!this.longPressAccount) {
					// uni.showToast({
					// 	title: '无法获取账号信息',
					// 	icon: 'none'
					// });
					return;
				}
				
				// 先保存账号数据，再关闭模态框
				const account = { ...this.longPressAccount };
				let copyText = `名称：${account.name || ''}\n`;
				copyText += `账号：${account.account || account.subtitle || ''}\n`;
				copyText += `密码：${account.password || ''}\n`;
				
				if (account.note && account.note.trim() !== '') {
					copyText += `备注：${account.note}\n`;
				}
				
				if (account.tag && account.tag.trim() !== '') {
					copyText += `标签：${account.tag}\n`;
				}
				
				// 复制自定义字段
				if (account.customFields && Object.keys(account.customFields).length > 0) {
					for (const [key, value] of Object.entries(account.customFields)) {
						if (value && value.trim() !== '') {
							copyText += `${key}：${value}\n`;
						}
					}
				}
				
				this.closeActionModal();
				
				uni.setClipboardData({
					data: copyText,
				showToast: false,
				success: () => {
					// uni.showToast({
					// 	title: '已复制全部内容',
					// 	icon: 'success',
					// 	duration: 2000
					// });
				},
					fail: () => {
						// uni.showToast({
						// 	title: '复制失败',
						// 	icon: 'none'
						// });
					}
				});
			},
			// 操作菜单 - 删除账号
			handleDeleteAccount() {
				if (!this.longPressAccount || !this.longPressAccount.id) {
					// uni.showToast({
					// 	title: '无法获取账号ID',
					// 	icon: 'none'
					// });
					return;
				}
				
				// 先保存账号数据，再关闭操作菜单，然后显示删除确认弹窗
				this.deleteAccountId = this.longPressAccount.id;
				this.deleteAccountName = this.longPressAccount.name || '此账号';
				
				this.closeActionModal();
				
				// 显示删除确认弹窗
				this.showDeleteConfirmModal = true;
			},
			// 关闭删除确认弹窗
			closeDeleteConfirmModal() {
				this.showDeleteConfirmModal = false;
				this.deleteAccountId = null;
				this.deleteAccountName = '';
			},
			// 确认删除账号
			confirmDeleteAccount() {
				if (!this.deleteAccountId) {
					// uni.showToast({
					// 	title: '无法获取账号ID',
					// 	icon: 'none'
					// });
					return;
				}
				
				try {
					const success = deleteAccount(this.deleteAccountId);
					if (success) {
						this.closeDeleteConfirmModal();
						this.loadData();
					} else {
						// uni.showToast({
						// 	title: '删除失败',
						// 	icon: 'none'
						// });
					}
				} catch (error) {
					// uni.showToast({
					// 	title: error.message || '删除失败',
					// 	icon: 'none'
					// });
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		width: 100%;
		height: 100vh;
		background-color: #FFFFFF;
		display: flex;
		flex-direction: column;
	}

	// 自定义导航栏
	.custom-navbar {
		background-color: #008D57;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 1000;
		width: 100%;
	}

	.navbar-content {
		height: 44px;
		display: flex;
		align-items: center;
		padding: 0 32rpx;
		color: #FFFFFF;
		gap: 24rpx;
	}

	.navbar-title {
		font-size: 32rpx;
		font-weight: 500;
		flex: 1;
	}

	.navbar-right {
		display: flex;
		align-items: center;
		gap: 32rpx;
		margin-left: auto;
	}

	.icon-wrapper {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 8rpx;
		cursor: pointer;
	}

	.icon-text {
		font-size: 36rpx;
		color: #FFFFFF;
		line-height: 1;
	}

	// 主内容区
	.main-content {
		flex: 1;
		display: flex;
		overflow: hidden;
		position: relative;
	}

	// 左侧分类列表
	.category-list {
		width: 200rpx;
		background-color: #FAFAFA;
		padding-top: 20rpx;
	}

	.category-item {
		padding: 24rpx 32rpx;
		font-size: 28rpx;
		color: #333333;
		transition: all 0.2s ease;
		cursor: pointer;
		position: relative;

		&.active {
			color: #008D57;
		}
		
		&:active {
			opacity: 0.7;
		}
	}

	.settings-icon {
		display: flex;
		align-items: center;
		justify-content: flex-start;
		cursor: pointer;
		
		&:active {
			opacity: 0.7;
		}
	}

	// 右侧账号列表
	.account-list {
		flex: 1;
		padding: 20rpx 0;
		margin-right: 40rpx;
	}

	.account-item {
		display: flex;
		align-items: center;
		padding: 24rpx 32rpx;
		background-color: #FFFFFF;
		border-bottom: 1px solid #F5F5F5;
	}

	.account-icon {
		width: 32rpx;
		height: 32rpx;
		border-radius: 6rpx;
		margin-right: 24rpx;
		flex-shrink: 0;
	}

	.account-info {
		flex: 1;
	}

	.account-name {
		font-size: 30rpx;
		color: #333333;
		margin-bottom: 8rpx;
	}

	.account-subtitle {
		font-size: 24rpx;
		color: #999999;
	}

	// 字母索引
	.alphabet-index {
		position: absolute;
		right: 0;
		top: 0;
		bottom: 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 20rpx 4rpx;
		z-index: 100;
		pointer-events: auto;
	}

	.index-star,
	.index-letter {
		font-size: 18rpx;
		color: #CCCCCC;
		padding: 2rpx 8rpx;
		line-height: 1.1;
		min-height: 24rpx;
		min-width: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.2s;
		border-radius: 8rpx;
		
		&.active {
			color: #008D57;
			font-weight: 600;
			font-size: 18rpx;
			background-color: #F5F5F5;
		}
	}

	.index-star {
		margin-bottom: 8rpx;
	}

	// 底部指示器
	.bottom-indicator {
		width: 80rpx;
		height: 4rpx;
		background-color: #CCCCCC;
		border-radius: 2rpx;
		margin: 20rpx auto;
	}
</style>
